//
//  NetworkTools+oAuth.swift
//  LEOweibo
//
//  Created by zz on 16/2/27.
//  Copyright © 2016年 zz. All rights reserved.
//

import Foundation

extension NetworkTools {
    
    var oAuthURL: NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlString)!
    }
    
    
    //获取用户accessToken
    func loadAccessToken(code: String, finished: ([String:AnyObject]?) -> ()){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]
        request(.POST, urlString: urlString, parameter: params) {[weak self]result in
            
            guard let result = result,
                let access_token = result["access_token"] as? String,
                let uid = result["uid"] as? String else{
                    finished(nil)
                    print("网络请求失败")
                    return
            }
            
             print("---------\(result)------")
            self?.loadUserInfo(access_token, uid: uid, finished: { (userDict) -> () in
                
                guard var userDict = userDict else {
                    print("用户数据加载错 误")
                    finished(nil)
                    return
                }
                
                for (k,v) in result {
                    userDict[k] = v
                }
                
                finished(userDict)
            })
        }
    }
}